<template>
  <BoTable
    :columns="columns"
    :request="getTerminalList"
    ref="tableRef"
    :row-selection="rowSelection"
    row-key="edgeId"
    show-index
  >
    <template #toolbars>
      <Space :size="8">
        <!-- <ImportModel @import-after="() => tableRef.refresh()"></ImportModel> -->
        <Button
          type="primary"
          :disabled="!selectKeys.length"
          @click="onDelete(null)"
        >
          删除
        </Button>
      </Space>
    </template>
  </BoTable>
  <FormModal :columns="items"></FormModal>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import {
  getDeviceManufacturerSelect,
  getDeviceModelSelect,
  getDevicePowerSelect,
} from '@/api';
import { deviceEnum } from '@/constants';
import { useFormModal } from '@boeyo/hooks';
import { useDicts } from '@boeyo/portal';
import { listToEnum, listToOption } from '@boeyo/shared';
import { BoFormProps, BoTable, BoTableProps } from '@boeyo/ui';
import { Button, Modal, Space, message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { deleteEdgeInfo, getTerminalList, updateEdgeInfo } from './api';
import Data from './components/Data.vue';
import ImportModel from './components/ImportModel.vue';

const router = useRouter();

const dictArr = [
  'device_type',
  'platform_type',
  'access_status',
  'online_status',
  'register_status',
  'device_manufacturer',
];
const { onlineStatusEnum, registerStatusEnum, platformTypeEnum } =
  useDicts(dictArr);

const tableRef = ref();
const selectKeys = ref<any[]>([]);
const rowSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    onChange(values, all) {
      selectKeys.value = values;
    },
  };
});

// 获取边缘终端厂商,型号
const mnufacturerOptions = ref<any[]>([]);
const manufacturerEnum = ref<Record<string, any>>({});
const modelOptions = ref<any[]>([]);
const modelEnum = ref<Record<string, any>>({});
const modelAllEnum = ref<Record<string, any>>({});
const powerOptions = ref<any[]>([]);
const powerEnum = ref<Record<string, any>>({});

const init = async () => {
  getDeviceManufacturerSelect(deviceEnum.TERMINAL).then(({ data }) => {
    mnufacturerOptions.value = listToOption(data, 'name', 'facId');
    manufacturerEnum.value = listToEnum(data, 'name', 'facId');
  });
  getDevicePowerSelect().then(({ data }) => {
    powerOptions.value = listToOption(data, 'powerSupplyName', 'id');
    powerEnum.value = listToEnum(data, 'powerSupplyName', 'id');
  });
  getDeviceModelSelect({ type: deviceEnum.TERMINAL }).then(({ data }) => {
    modelAllEnum.value = listToEnum(data, 'model', 'modelId');
  });
};
init();

const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '边缘设备编号',
    dataIndex: 'edgeCode',
  },
  {
    title: '注册状态',
    dataIndex: 'registerStatus',
    valueEnum: registerStatusEnum.value,
    valueType: 'status',
    hideInSearch: true,
  },
  {
    title: '在线状态',
    dataIndex: 'onlineStatus',
    valueEnum: onlineStatusEnum.value,
    valueType: 'status',
  },
  {
    title: '边缘设备型号',
    dataIndex: 'model',
    hideInSearch: true,
  },
  {
    title: '边缘设备型号',
    dataIndex: 'modelId',
    valueEnum: modelAllEnum.value,
    valueType: 'select',
    hideInTable: true,
  },
  {
    title: '设备厂商',
    dataIndex: 'manufacturer',
    hideInSearch: true,
    ellipsis: true,
  },
  {
    title: '设备厂商',
    dataIndex: 'facId',
    valueType: 'select',
    valueEnum: manufacturerEnum.value,
    hideInTable: true,
  },
  {
    title: '平台类型',
    dataIndex: 'platformType',
    valueType: 'select',
    valueEnum: platformTypeEnum.value,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    hideInSearch: true,
  },
  {
    title: '创建人',
    dataIndex: 'createBy',
    hideInSearch: true,
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    hideInSearch: true,
  },
  {
    title: '更新人',
    dataIndex: 'updateBy',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    actions: [
      // {
      //   text: '远程控制',
      //   onClick(record) {
      //     onRemoteControl(record);
      //   },
      // },
      {
        text: '详情',
        onClick(record) {
          onView(record);
        },
      },
      {
        text: '删除',
        onClick(record) {
          onDelete(record);
        },
      },
    ],
  },
]);

const items = computed<BoFormProps['columns']>(() => [
  {
    title: '厂商',
    dataIndex: 'facId',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择厂商',
          trigger: 'blur',
        },
      ],
    },
    fieldProps(state) {
      return {
        placeholder: '请选择厂商',
        options: mnufacturerOptions.value,
        onChange(facId) {
          getDeviceModelSelect({ facId: facId as number, type: 3 }).then(
            ({ data }) => {
              modelOptions.value = listToOption(data, 'model', 'modelId');
              modelEnum.value = listToEnum(data, 'model', 'modelId');
              state.modelId = undefined;
            },
          );
        },
      };
    },
  },
  {
    title: '型号',
    dataIndex: 'modelId',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请输入设备型号',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入设备型号',
      options: modelOptions.value,
    },
  },
  {
    title: '电源',
    dataIndex: 'powerSupplyId',
    valueType: 'select',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '请选择边缘终端电源',
          trigger: 'blur',
        },
      ],
    },
    fieldProps: {
      placeholder: '请输入边缘终端电源',
      options: powerOptions.value,
    },
  },
  {
    title: '设备IP',
    dataIndex: 'ip',
    valueType: 'input',
    fieldProps: {
      disabled: true,
    },
  },
  {
    title: '',
    dataIndex: '__custom',
    valueType: 'input',
    colProps: { span: 24 },
    formItemRender(state) {
      const { diskUsageMap } = caculateDiskUse(state.diskUsage);

      return () => (
        <Data
          cpuTemperature={state.cpuTemperature}
          cpuUsage={JSON.parse(state.cpuUsage)}
          memUsage={state.memUsage}
          diskUsage={diskUsageMap}
        />
      );
    },
  },

  // {
  //   title: 'CPU运行温度（°C）',
  //   dataIndex: 'cpuTemperature',
  //   valueType: 'input',
  //   fieldProps: {
  //     disabled: true,
  //   },
  // },
  // {
  //   title: 'CPU使用率（%）',
  //   dataIndex: 'cpuUsage',
  //   valueType: 'input',
  //   fieldProps: {
  //     disabled: true,
  //   },
  // },
  // {
  //   title: '内存使用率（%）',
  //   dataIndex: 'memUsage',
  //   valueType: 'input',
  //   fieldProps: {
  //     disabled: true,
  //   },
  // },
  // {
  //   title: '磁盘使用率',
  //   dataIndex: 'diskUsage',
  //   valueType: 'input',
  //   colProps: {
  //     span: 24,
  //   },
  //   formItemProps: {
  //     labelCol: {
  //       span: 3,
  //     },
  //     wrapperCol: {
  //       span: 18,
  //     },
  //   },
  //   formItemRender() {
  //     return <div class='module-title'>磁盘使用率</div>;
  //   },
  // },
  // {
  //   title: '',
  //   dataIndex: 'diskUsage',
  //   valueType: 'input',
  //   fieldProps: {
  //     disabled: true,
  //   },
  //   colProps: {
  //     span: 24,
  //   },
  //   formItemProps: {
  //     labelCol: {
  //       span: 0,
  //     },
  //     wrapperCol: {
  //       span: 24,
  //     },
  //   },
  //   render(state) {
  //     const { diskUsageMap, columns } = caculateDiskUse(state.diskUsage);
  //     return diskUsageMap.length > 0 ? (
  //       <Table
  //         columns={columns}
  //         dataSource={diskUsageMap}
  //         pagination={false}
  //       ></Table>
  //     ) : (
  //       <span>--</span>
  //     );
  //   },
  // },
]);

// 计算磁盘使用率
const caculateDiskUse = (disk: string) => {
  // 去掉 [ 和 ]
  const cleanedDiskUsage = disk?.replace(/^\[|\]$/g, '');
  // 按 , 分割成单独的元素
  const items = cleanedDiskUsage?.split(',')?.map((item) => item.trim());
  // 处理每个元素
  const diskUsageMap =
    items?.map((item) => {
      const cleanedItem = item.replace(/{|}/g, ''); // 去掉 { 和 }
      const [disk, usage] = cleanedItem.split('='); // 按 = 分割
      return {
        disk,
        usage,
      }; // 拼接成 disk usage 格式
    }) || [];
  const columns = [
    {
      title: '磁盘',
      dataIndex: 'disk',
      align: 'center',
    },
    {
      title: '使用率',
      dataIndex: 'usage',
      align: 'center',
    },
  ];
  return {
    diskUsageMap,
    columns,
  };
};

const { FormModal, open } = useFormModal({
  size: 'middle',
  column: 2,
  formProps: {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  },
});

const onView = async (record) => {
  // 根据facId获取model型号下拉框数据
  getDeviceModelSelect({ facId: record.facId as number, type: 3 }).then(
    ({ data }) => {
      modelOptions.value = listToOption(data, 'model', 'modelId');
      modelEnum.value = listToEnum(data, 'model', 'modelId');
    },
  );
  open({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType: 'info',
    defaultValue: record,
    request: async (params: any) => {
      await updateEdgeInfo(params);
      tableRef.value.refresh();
    },
  });
};

const onDelete = (record?: any) => {
  const ids = record ? record.edgeId : selectKeys.value.join();
  if (!ids) return message.info('请选择要删除的数据');
  Modal.confirm({
    title: '删除',
    content: '确定删除当前选中项数据吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      await deleteEdgeInfo(ids);
      message.success('删除成功');
      tableRef.value.refresh();
    },
  });
};
const onRemoteControl = (record) => {
  router.push({
    name: 'terminal-remote-control',
    state: {
      ...record,
    },
  });
};
</script>
<route lang="json">
{
  "name": "terminal",
  "meta": { "title": "边缘终端远程控制" }
}
</route>
